package com.sdyeda.dtu.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sdyeda.tool.HexTools;

public class DtuClientThread extends Thread {

	Object lock =0;
	
	private Socket socket = null;

	private final Log log = LogFactory.getLog(this.getClass());
	
	public DtuClientThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			// OutputStream writer = socket.getOutputStream();
			InputStream reader = socket.getInputStream();
			//int len =0;
			//byte[] buff = new byte[1024];
			while (true) {

				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
				}

				int availnum = reader.available();
				
				if (availnum > 0) {
					byte[] buff = new byte[availnum];
					int ret = reader.read(buff);
					//System.out.print(ret+"++dtu::"+HexTools.bytesToHex(buff));
					log.info("DTU:"+HexTools.bytesToHex(buff));
					
					if (ret > 0) {
						synchronized (lock) {
							//读取传感器
							if(ret ==6) {	//DTU编号——心跳信号
								//System.out.println(HexTools.bytesToHex(buff));
								Server.updateDtuId(socket,HexTools.bytesToHex(buff));
								if(Server.getIotclients().size()==0) {  //回复DTU心跳
									//0.
									replyDTU();
								}
							}
							//查找接入的传感器
							IotInfo iot = IotInfo.getIotInfo(buff);
							if(iot !=null) {
								Server.updateIot(socket,iot);
							}
							
							send(buff, ret);
						}
					}
				}
				
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		//
	}
	

	void send(byte[] buff, int length) {
		List<Socket> list = Server.getIotclients();
		if (list != null) {
			list.forEach(item -> {
				if (item.isConnected() || !item.isClosed()) {
					try {
						item.getOutputStream().write(buff, 0, length);
					} catch (IOException e) {		//掉线
						try {
							item.shutdownOutput();
						}catch(IOException e1) {
							//e1.printStackTrace();
						}
						//e.printStackTrace();
					}
				}
			});
		}
	}
	
	//回复DTU  00 为了清除断开的DTU
	void replyDTU() {
		List<DtuInfo> list = Server.getDtuclients();
		if(list==null)
			return;
		list.forEach(item->{
			if (item.getSocket().isConnected() || !item.getSocket().isClosed()) {
				try {
					byte[] buff = new byte[1];
					item.getSocket().getOutputStream().write(buff, 0, 1);
				} catch (IOException e) {
					try {
						item.getSocket().shutdownOutput();
					} catch (IOException e1) {
					}
				}
			}
		});
	}

}
